package com.kingmed.kmss.admin.modules.ums.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kingmed.kmss.admin.modules.ums.model.UmsAdmin;
import com.kingmed.kmss.admin.modules.ums.model.UmsAdminOrganizationRelation;
import com.kingmed.kmss.admin.modules.ums.model.UmsKmcsOrg;
import com.kingmed.kmss.admin.modules.ums.model.UmsOrganization;
import com.kingmed.kmss.admin.modules.ums.service.UmsAdminService;
import com.kingmed.kmss.admin.modules.ums.service.UmsKmcsOrgService;
import com.kingmed.kmss.admin.modules.ums.service.UmsOrganizationService;
import com.kingmed.kmss.admin.qc.AdminQc;
import com.kingmed.kmss.common.dto.admin.ums.OrgNodeDTO;
import com.kingmed.kmss.common.dto.admin.ums.OrganizationDTO;
import com.kingmed.kmss.common.dto.admin.ums.OrganizationTileDTO;
import com.kingmed.kmss.common.utils.BeanCopyUtils;
import com.kingmed.kmss.common.vo.CommonResponse;
import com.kingmed.kmss.common.vo.CommonResponseHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 后台组织机构表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/ums/organization")
@Api(tags = "ums组织部门管理")
public class UmsOrganizationController {

    @Autowired
    private UmsOrganizationService umsOrgService;
    @Autowired
    private UmsAdminService umsAdminService;

    @Autowired
    private UmsKmcsOrgService umsKmcsOrgService;

    @ApiOperation("OrgID查子公司信息")
    @GetMapping(value = "/getBranch")
    public CommonResponse<UmsOrganization> getBranch(@RequestParam("orgId") Long orgId) {
        List<UmsOrganization> allOrg = umsOrgService.loadAllOrg();
        UmsOrganization branch = umsOrgService.getBranchOrg(allOrg, orgId);
        if (BeanUtil.isEmpty(branch)) {
            return CommonResponseHelper.success("当前节点是大区或者总部");
        }
        return CommonResponseHelper.success(branch);
    }

    @ApiOperation("OrgID查上级组织信息")
    @GetMapping(value = "/getParentUp")
    public CommonResponse<List<UmsOrganization>> getParentUp(@RequestParam("orgId") Long orgId) {
        List<UmsOrganization> allOrg = umsOrgService.loadAllOrg();
        List<UmsOrganization> parentUpList = umsOrgService.getParentUpList(allOrg, orgId);
        if (BeanUtil.isEmpty(parentUpList)) {
            return CommonResponseHelper.success("当前是顶级节点");
        }
        return CommonResponseHelper.success(parentUpList);
    }

    @ApiOperation("用户ID查上级组织部门信息")
    @GetMapping(value = "/getParentUpByAdminId")
    public CommonResponse<List<UmsOrganization>> getParentUpByAdminId(@RequestParam("adminId") Long adminId) {
        List<UmsOrganization> orgList = umsAdminService.getOrgList(adminId);
        // 一个用户只有一个组织
        if (CollUtil.isNotEmpty(orgList)) {
            List<UmsOrganization> allOrg = umsOrgService.loadAllOrg();
            List<UmsOrganization> parentUpList = umsOrgService.getParentUpList(allOrg, orgList.get(0).getId());
            //顶级节点，把顶级节点返回去
            if (CollUtil.isEmpty(parentUpList)) {
                return CommonResponseHelper.success("当前是顶级节点", orgList);
            }
            orgList.addAll(parentUpList);
            return CommonResponseHelper.success(orgList);
        }
        return CommonResponseHelper.success("没有相关数据");
    }

    @ApiOperation("用户ID获取全部子公司：有权限看到的所有子公司")
    @GetMapping(value = "/getSubsidiaryByAdminId")
    public CommonResponse<List<OrganizationDTO>> getSubsidiaryByAdminId(@RequestParam("adminId") Long adminId) {
        return CommonResponseHelper.success(umsOrgService.getSubsidiaryByAdminId(adminId));
    }

    @ApiOperation("组织ID获取全部子公司：有权限看到的所有子公司")
    @GetMapping(value = "/getBranchesByOrgId")
    public CommonResponse<List<OrganizationDTO>> getBranchesByOrgId(@RequestParam("orgId") Long orgId) {
        return CommonResponseHelper.success(umsOrgService.getBranchesByOrgId(orgId));
    }

    @ApiOperation("根据adminId获取全部子公司：有权限看到的所有子公司")
    @GetMapping(value = "/getBranchesByAdminId")
    public CommonResponse<List<OrganizationDTO>> getBranchesByAdminId(@RequestParam("adminId") Long adminId) {
        return CommonResponseHelper.success(umsAdminService.getBranchesByAdminId(adminId));
    }

    @ApiOperation("组织树（全部层级）")
    @GetMapping(value = "/orgAndChildTree")
    public CommonResponse<OrgNodeDTO> orgAndChildTree(@RequestParam("orgId") Long orgId) {
        return CommonResponseHelper.success(umsOrgService.tree(orgId));
    }

    @ApiOperation("组织结构树（3层级以上）")
    @GetMapping(value = "/getOrgAndChildTree/{orgId}")
    public CommonResponse<OrgNodeDTO> getOrgAndChildTree(@PathVariable Long orgId) {
        return CommonResponseHelper.success(umsOrgService.levelThreeOrgTree());
    }

    @ApiOperation("组织结构树（3层级以下）")
    @GetMapping(value = "/get4LevelOrgAndChild/{orgId}")
    public CommonResponse<OrgNodeDTO> get4LevelOrgAndChild(@PathVariable Long orgId,
                                                           @RequestParam(value = "onlyOrg", defaultValue = "false") Boolean onlyOrg) {
        return CommonResponseHelper.success(umsOrgService.tree4Level(orgId, onlyOrg));
    }

    @ApiOperation("根据ID查下级组织列表")
    @GetMapping(value = "/orgAndChild")
    public CommonResponse<List<OrgNodeDTO>> orgAndChild(@RequestParam("orgId") Long orgId) {
        return CommonResponseHelper.success(umsOrgService.selfAndChild(orgId));
    }

    @ApiOperation("根据名称模糊查询组织机构")
    @GetMapping(value = "/getByNameKey")
    public CommonResponse<List<UmsOrganization>> getByNameKey(@RequestParam(value = "keyword", required = false) String keyword) {
        return CommonResponseHelper.success(umsOrgService.getByNameKey(keyword));
    }

    @ApiOperation("修改组织机构信息")
    @PostMapping(value = "/updateOrg")
    @ResponseBody
    public CommonResponse<List<UmsOrganization>> updateOrg(@RequestBody OrgNodeDTO orgNodeDto) {
        return CommonResponseHelper.success(umsOrgService.updateOrg(orgNodeDto));
    }

    @ApiOperation("删除组织机构")
    @PostMapping(value = "/deleteOrg")
    public CommonResponse<Integer> deleteOrg(@RequestBody List<Long> orgIdList) {
        return CommonResponseHelper.success(umsOrgService.deleteOrg(orgIdList));
    }

    @ApiOperation("生效组织机构")
    @PostMapping(value = "/availableOrg")
    public CommonResponse<Integer> availableOrg(@RequestBody List<Long> orgIdList) {
        return CommonResponseHelper.success(umsOrgService.availableOrg(orgIdList));
    }

    @ApiOperation("组织机构下用户")
    @GetMapping(value = "/adminsInOrg")
    public CommonResponse<List<UmsAdmin>> adminsInOrg(@RequestParam("orgId") Long orgId) {
        return CommonResponseHelper.success(umsOrgService.adminsInOrg(orgId));
    }

    @ApiOperation("组织机构及下级组织机构用户：分页")
    @PostMapping(value = "/adminsInOrgAndChild")
    public CommonResponse<Page<UmsAdmin>> adminsInOrgAndChild(@RequestBody AdminQc adminQc) {
        return CommonResponseHelper.success(umsOrgService.adminsInOrgAndChild(adminQc));
    }

    @ApiOperation("组织机构及下级组织机构用户:不分页")
    @PostMapping(value = "/allAdminsInOrg")
    public CommonResponse<List<UmsAdmin>> allAdminsInOrg(@RequestBody AdminQc adminQc) {
        return CommonResponseHelper.success(umsOrgService.allAdminsInOrg(adminQc));
    }

    @ApiOperation("添加用户与组织的关系")
    @PostMapping(value = "/addAdminsInOrg")
    public CommonResponse<String> addAdminsInOrg(@RequestBody List<UmsAdminOrganizationRelation> relations) {
        umsOrgService.addAdminsInOrg(relations);
        return CommonResponseHelper.success();
    }

    @ApiOperation("删除用户与组织的关系")
    @PostMapping(value = "/deleteAdminsInOrg")
    @Transactional
    public CommonResponse<String> deleteAdminsInOrg(@RequestBody List<UmsAdminOrganizationRelation> relations) {
        umsOrgService.deleteAdminsInOrg(relations);
        return CommonResponseHelper.success();
    }

    @ApiOperation("所属集团、大区、子公司平铺ByOrgID")
    @GetMapping(value = "/getGroupRegionBranchByOrgId")
    public CommonResponse<OrganizationTileDTO> getOrgGroupRegionSubCompByOrgId(@RequestParam Long orgId) {
        return CommonResponseHelper.success(umsOrgService.getOrgGroupRegionBranchByOrgId(orgId));
    }

    @ApiOperation("所属集团、大区、子公司平铺ByAdminID")
    @GetMapping(value = "/getGroupRegionBranchByAdminId")
    public CommonResponse<OrganizationTileDTO> getGroupRegionBranchByAdminId(@RequestParam Long adminId) {
        return CommonResponseHelper.success(umsAdminService.getGroupRegionBranchByAdminId(adminId));
    }

    @ApiOperation("有权限的组织树（用户ID）")
    @GetMapping(value = "/queryPermissionOrg")
    public CommonResponse<OrgNodeDTO> queryPermissionOrg(@RequestParam("adminId") Long adminId) {
        return CommonResponseHelper.success(umsOrgService.queryPermissionOrg(adminId));
    }

    @ApiOperation("有权限的组织树（组织ID）")
    @GetMapping(value = "/queryPermissionByOrgId")
    public CommonResponse<OrgNodeDTO> queryPermissionByOrgId(@RequestParam("orgId") Long orgId) {
        return CommonResponseHelper.success(umsOrgService.queryPermissionByOrgId(orgId));
    }

    @ApiOperation("获取所有大区")
    @GetMapping(value = "/getRegions")
    public CommonResponse<List<OrganizationDTO>> getRegions() {
        return CommonResponseHelper.success(umsOrgService.getRegionsBySql());
    }


    @ApiOperation("获取所有子公司")
    @GetMapping(value = "/getAllBranch")
    public CommonResponse<List<OrganizationDTO>> getAllBranch() {
        return CommonResponseHelper.success(umsOrgService.getAllSubsidiary());
    }

    @ApiOperation("获取组织结构直属下级")
    @GetMapping(value = "/directchild")
    public CommonResponse<List<OrgNodeDTO>> directChild(@RequestParam("orgId") Long orgId) {
        return CommonResponseHelper.success(umsOrgService.directChild(orgId));
    }

    @ApiOperation("获取组织结构详情")
    @GetMapping(value = "/detail")
    public CommonResponse<OrgNodeDTO> detail(@RequestParam("orgId") Long orgId) {
        OrgNodeDTO nodeDto = BeanCopyUtils.copy(umsOrgService.getBaseMapper().selectById(orgId), OrgNodeDTO.class);
        if (nodeDto != null) {
            nodeDto.setHasChildren(true);
        }
        return CommonResponseHelper.success(nodeDto);
    }

    @ApiOperation("集团、大区、子公司单列表(营销活动日历功能用)")
    @GetMapping(value = "/groupRegionBranch")
    public CommonResponse<List<OrganizationDTO>> groupRegionBranch(@RequestParam(required = false) Integer orgLevel) {
        return CommonResponseHelper.success(umsOrgService.groupRegionBranch(orgLevel));
    }


    /**
     * 通过子公司名称查询子公司信息, 通过大区名称查询大区信息
     */
    @ApiOperation("通过子公司名称查询子公司信息,通过大区名称查询大区信息")
    @GetMapping(value = "/getOrgByName")
    public CommonResponse<List<OrganizationDTO>> getOrgByName(@RequestParam(value = "branchName", required = false) String branchName,
                                                              @RequestParam(value = "regionName", required = false) String regionName) {
        List<UmsOrganization> orgList = umsOrgService.list(new QueryWrapper<UmsOrganization>().lambda()
                .eq(StrUtil.isNotBlank(branchName), UmsOrganization::getOrgName, branchName)
                .eq(StrUtil.isNotBlank(regionName), UmsOrganization::getOrgName, regionName));
        List<OrganizationDTO> organizationDTOS = BeanCopyUtils.copyList(orgList, OrganizationDTO.class);
        organizationDTOS.forEach(t -> {
            Long companyId = t.getCompanyId();
            UmsKmcsOrg one = umsKmcsOrgService.getOne(new LambdaQueryWrapper<UmsKmcsOrg>().eq(UmsKmcsOrg::getOrgId, companyId).last("limit 1"));
            t.setKmcsCode(one.getKmcsCode());
            t.setKmcsName(one.getKmcsName());
            t.setOrgShortName(one.getOrgShortName());
        });
        return CommonResponseHelper.success(organizationDTOS);
    }

}
